package com.example.wujinapi.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wujinapi.comm.*;
import com.example.wujinapi.entity.Users;
import com.example.wujinapi.entity.wxDecryptPhoneUser;
import com.example.wujinapi.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (Users)表控制层
 *
 * @author makejava
 * @since 2023-03-04 21:55:22
 */
@RestController
@RequestMapping("/")
public class indexController {
    /**
     * 服务对象
     */
    @Resource
    private UsersService usersService;

    @Autowired
    private RedisUtils redisUtils;

    @Resource
    HttpServletRequest request;

    @Resource
    private PcadvertisingService pcadvertisingService;


    @PostMapping("/wxLogin")
    public R wxLogin(@RequestBody Users users) throws Exception {
        //System.out.println("对象:"+users);
        //System.out.println(JSON.toJSONString(users));
        String res= WeChat.getOpenid(users.getLogincode()); //"{\"session_key\":\"J9Hx6Fsilt5pC0k8cObTDQ==\",\"openid\":\"obol15E5sxeKYl0X7BbXQzFXWKjw\"}"
        if(!StringUtils.isEmpty(res)){
            //获取openid和sessionKey
            String openid=JSON.parseObject(res).getString("openid");
            String SessionKey=JSON.parseObject(res).getString("session_key");
            if(!StringUtils.isEmpty(openid) && !StringUtils.isEmpty(SessionKey)) {
                Map<String, String> keys = new HashMap<String, String>();
                //注册用户
                Users ur=new Users();
                ur.setWxopenid(openid);
                ur.setHeadimg("https://aigxyy.oss-cn-shenzhen.aliyuncs.com/images/mine/%E6%9B%B4%E6%96%B0%E5%A4%B4%E5%83%8F.png"); //默认头像
                ur.setUsername("微信用户");
                usersService.addUser(ur);

                //读取用户信息
                Users userinfo=usersService.readUserByOpenid(openid);

                keys.put("userid", String.valueOf(userinfo.getId()));
                keys.put("openid", openid);
                keys.put("SessionKey", SessionKey);
                String Token = jwtUtils.createToken(keys);
                //System.out.println("生成token===========>" + Token);

                //返回数据到客户端
                HashMap<String,Object> map = new HashMap<String,Object>();
                map.put("token",Token);
                map.put("userinfo",userinfo);

                return R.ok().put("data", map);
            }else{
                return R.error(400,"微信授权登录失败");
            }
        }else{
            return R.error(400,"登录失败");
        }
    }
    /**
     * 小程序解密
     */
    @PostMapping("/wxDecryptPhone")
    public R wxDecryptPhone(@RequestBody wxDecryptPhoneUser datas) throws Exception {
        //System.out.println("接收解密参数："+datas);
        if(datas.getToken()==null){
            return R.error(400,"登录失败,无效的凭证");
        }
        return usersService.wxDecryptPhone(datas.getToken(), datas.getEncryptedData(), datas.getIv());
    }


    /**
     * 读取首页轮播图
     */
    @PostMapping("/readSwiper")
    public R readSwiper() throws Exception {
        try {
            List<Map<String, Object>> swiperimgLists=pcadvertisingService.ReadPcad();
            return R.ok("读取轮播图成功").put("swiperimgLists",swiperimgLists);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("读取轮播图失败!!!");
        }
    }

}

